package org.shana.shortlink.admin.remote;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

public interface LinkGotoRemoteService {

    default void restoreUrl(String url, ServletRequest request, ServletResponse response) throws ServletException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpGet httpGet = new HttpGet("http://127.0.0.1:8081/" + url);

            // 复制原始请求的头信息到新的请求
            Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = httpServletRequest.getHeader(headerName);
                // 过滤掉不需要传递的头信息，例如Host
                if (!"host".equalsIgnoreCase(headerName)) {
                    httpGet.setHeader(new BasicHeader(headerName, headerValue));
                }
            }

            // 执行请求
            HttpResponse remoteResponse = httpClient.execute(httpGet);
            HttpEntity entity = remoteResponse.getEntity();
            if (entity != null) {
                // 设置响应内容类型
                response.setContentType(entity.getContentType().getValue());
                // 将远程响应体写入当前响应
                response.getWriter().write(EntityUtils.toString(entity));
            }
        } finally {
            httpClient.close();
        }
    }
}
